layui.use(['form', 'layer', 'table', 'tree'], function () {

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        tree = layui.tree,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var check_name_url = $('.check_name_url').val();
    var save_url = $('.save_url').val();
    var handle_url = $('.handle_url').val();
    var getMenus_url = $('.getMenus_url').val();


    if ($('#dataTable').length > 0) {
        // Table 列表
        var tableIns = table.render({
            elem: '#dataTable',
            url: datalist_url,
            page: true,
            cellMinWidth: 95,
            //height : "full-100",
            limit: 10,
            limits: [10, 20, 50, 100],
            id: "tableList",
            cols: [[
                /*{type: "checkbox", fixed:"left", width:50},*/
                {field: 'id', title: '序号', width: 80, align: "center"},
                {field: 'name', title: '角色名称', align: "center"},
                {
                    field: 'status', title: '禁用与启用', align: "center", templet: function (data) {
                        var html = '';
                        if (data.status == 1) {
                            html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="' + data.id + '" checked>';
                        } else {
                            html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="' + data.id + '">';
                        }

                        return html;
                    }
                },
                {
                    title: '操作', fixed: "right", align: "center", minWidth: 140, templet: function (data) {
                        var html = '';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';

                        return html;
                    }
                }
            ]]
        });

        // 搜索
        $(".search_btn").on("click", function () {
            var name = $('.searchBox').find('input[name=name]').val();

            if (name != '') {
                table.reload("tableList", {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                        name: name,
                    }
                });
            } else {
                layer.msg("请选择筛选条件");
            }
        });

        // 清空搜索
        $(".reset_btn").on("click", function () {
            table.reload("tableList", {
                where: {
                    name: '',
                }
            });
        });

        $('.add_btn').on('click', function () {
            formHtml();
        });

        // 列表操作
        table.on('tool(dataTable)', function (obj) {
            var layEvent = obj.event,
                data = obj.data;
            // 删除
            if (layEvent === 'del') {
                layer.confirm('确定删除此数据？', {icon: 3, title: '提示信息'}, function (index) {
                    $.ajax({
                        url: delete_url,
                        data: {"id": data.id},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            if (res.status == 1) {
                                layer.msg('已删除', {icon: 1, time: 1000});
                                tableIns.reload();
                                layer.close(index);
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });
                });
            } else if (layEvent === 'edit') {
                formHtml(data);
            }
        });
    }

    // Form 表单
    function formHtml(data) {
        var content = add_url;

        if (data) {
            content = edit_url + '?id=' + data.id;
        }

        var index = layer.open({
            title: "角色管理",
            type: 2,
            area: ["600px", "500px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    }

    form.on('switch(status)', function (data) {
        var index = layer.msg('修改中，请稍候', {icon: 16, time: false, shade: 0.8});

        var status = 2;
        if (data.elem.checked) {
            status = 1;
        }
        $.ajax({
            url: handle_url,
            data: {'id': data.elem.value, 'status': status},
            type: "post",
            dataType: "json",
            success: function (res) {
                top.layer.close(index);
                top.layer.msg(res.msg);
                if (res.status == 1) {
                    parent.layui.table.reload('tableList', {});
                } else {
                    data.elem.checked = !data.elem.checked;
                    form.render();
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    });

    if ($('#role_tree').length > 0) {
        var id = $('input[name=id]').val();
        if (id) {
            getMenus_url += '?id=' + id;
        }

        $.get(
            getMenus_url,
            function (res) {
                //console.log(res);
                var data = res;
                layui.role_tree = tree.render({
                    elem: '#role_tree',  // 绑定元素
                    id: 'roleTree', // 定义索引
                    data: data,
                    showCheckbox: true,
                    oncheck: function (obj) {
                        //console.log(obj.data); //得到当前点击的节点数据
                        //console.log(obj.checked); //得到当前节点的展开状态：open、close、normal
                        //console.log(obj.elem); //得到当前节点元素
                    }
                });
            }
        );

        // 获取选中节点的id
        function get_checked_list(data) {
            var ids = [];
            $.each(data, function (index, item) {
                /*if (ids != '') {
                    ids = ids + ',' + item.id;
                } else {
                    ids = item.id;
                }
                var child = get_checked_list(item.children);
                if (child != '') {
                    ids = ids + ',' + child;
                }*/
                ids.push(item.id);
                var child = get_checked_list(item.children);
                if (child.length > 0) {
                    ids.push.apply(ids, child);
                }
            });

            return ids;
        }
    }

    // 表单提交
    form.on("submit(laySave)", function (data) {
        // 获得选中的节点
        var checkedData = tree.getChecked('roleTree');
        if (checkedData.length <= 0) {
            layer.msg("至少选择一项权限");
            return false;
        }
        //var role_list = get_checked_list(checkedData);
        //data.field.access = role_list;

        if (data.field.status == 'on') {
            data.field.status = 1;
        } else {
            data.field.status = 2;
        }

        var name = $('.name').val();
        var ori_name = $('.name').attr('data-name');
        if (name != ori_name) {
            var url = check_name_url;
            $.ajax({
                url: url,
                type: 'POST',
                data: {'name': name},
                dataType: 'json',
                success: function (res) {
                    if (res.status == 1) {
                        layer.msg('该名称已经存在！', {icon: 5});
                        $('.username').focus();
                        return false;
                    } else {
                        submitForm(data);
                    }
                }
            });
            return false;
        }

        submitForm(data);
    });

    // 表单提交
    function submitForm(data) {
        // 弹出loading
        var index = layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function (res) {
                layer.msg(res.msg);
                if (res.status == 1) {
                    layer.closeAll("iframe");
                    //parent.window.tableIns.reload();
                    parent.layui.table.reload('tableList', {});
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    }
});